# HarmonyOS App Deployment Script (Using Existing HAP)
# Make sure hdc is connected to device before running

# App bundle name
$BUNDLE_NAME = "com.example.work0907"
# Path to existing HAP file
$ENTRY_HAP = "entry\build\default\outputs\default\entry-default-unsigned.hap"
# Temporary directory name (random string to avoid conflicts)
$TMP_DIR = "hm_deploy_tmp_" + [System.Guid]::NewGuid().ToString("N").Substring(0, 16)

# Stop on error
$ErrorActionPreference = "Stop"

try {
    Write-Host "1. Checking if HAP file exists..."
    if (-Not (Test-Path $ENTRY_HAP)) {
        throw "HAP file not found: $ENTRY_HAP"
    }
    Write-Host "  ✓ HAP file found"

    Write-Host "2. Stopping running application..."
    try {
        hdc shell aa force-stop "$BUNDLE_NAME"
        Write-Host "  ✓ Application stopped"
    } catch {
        Write-Host "  ○ Application not running or stop failed, continuing..."
    }

    Write-Host "3. Creating temporary directory on device..."
    hdc shell mkdir -p "data/local/tmp/$TMP_DIR"
    Write-Host "  ✓ Temporary directory created"

    Write-Host "4. Transferring HAP file to device..."
    hdc file send "$ENTRY_HAP" "data/local/tmp/$TMP_DIR/entry-default-unsigned.hap"
    Write-Host "  ✓ HAP file transferred"

    Write-Host "5. Installing application package..."
    hdc shell bm install -p "data/local/tmp/$TMP_DIR"
    Write-Host "  ✓ Application installed"

    Write-Host "6. Cleaning up temporary files on device..."
    hdc shell rm -rf "data/local/tmp/$TMP_DIR"
    Write-Host "  ✓ Temporary files cleaned up"

    Write-Host "7. Starting application..."
    hdc shell aa start -a EntryAbility -b "$BUNDLE_NAME" -m entry
    Write-Host "  ✓ Application started"

    Write-Host "✅ Deployment completed! Application has been successfully started"

} catch {
    Write-Host "❌ Deployment failed: $($_.Exception.Message)"
    Write-Host "Please check error message and try again, make sure hdc is properly connected to device"
    exit 1
}